package zju.lzy.controller;


import com.alibaba.fastjson.JSONObject;
import com.sun.corba.se.impl.protocol.giopmsgheaders.RequestMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import zju.lzy.dto.Device;
import zju.lzy.dto.ResponseMessage;
import zju.lzy.mapper.DeviceMapper;
import zju.lzy.service.device.DeviceService;
import zju.lzy.service.message.MessageReceiver;

import java.util.List;

@RestController
public class DeviceController {

    private static final Logger logger = LoggerFactory.getLogger(DeviceController.class);

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private MessageReceiver messageReceiver;

    @Autowired
    private DeviceMapper deviceMapper;

    @GetMapping("/addDevice")
    ResponseMessage addDevice(Integer ownerId,
                              String topic,
                              String clientPrefix,
                              @RequestParam(required = false, defaultValue = "2")
                                      int qos,
                              @RequestParam(required = false, defaultValue = "119.9")
                                      double initLon,
                              @RequestParam(required = false, defaultValue = "30.1")
                                      double initLat,
                              @RequestParam(required = false, defaultValue = "true")
                                      String isActive) {


        Integer deviceId;
        boolean success;
        System.out.println(" " + ownerId + " " + topic + " " + clientPrefix);
        synchronized (this) {
            deviceId = deviceMapper.getLastIncrement();
            success = deviceMapper.createDevice(ownerId, clientPrefix, topic, qos, initLat, initLon, "true".equals(isActive));
        }
        // 数据库插入成功再进行缓存内操作
        if (success &&
                deviceService.startDevice(new Device(deviceId, ownerId, clientPrefix, topic, qos, initLat, initLon, Boolean.parseBoolean(isActive)))) {
            messageReceiver.subscribeTopic(topic);
            return new ResponseMessage(true, "创建设备成功！", null);
        }
        return new ResponseMessage(false, "创建设备失败", null);
    }

    @PostMapping("/startDevice")
    ResponseMessage startDevice(@RequestBody Device device) {
        Integer deviceId = device.getDeviceId();
        if (!device.isActive()
                && deviceService.startDevice(device)
                && deviceMapper.startDevice(deviceId)) {
        }
        // 让接收端订阅device的消息
        messageReceiver.subscribeTopic(device.getTopic());
        return new ResponseMessage(true, "设备开启成功", null);
    }


    @PostMapping("/stopDevice")
    ResponseMessage stopDevice(@RequestBody Device device) {
        Integer deviceId = device.getDeviceId();
        if (device.isActive() && deviceMapper.stopDevice(deviceId)) {
            device.setActive(false);
            deviceService.stopDevice(deviceId);
            logger.info("停止指定设备成功");
            return new ResponseMessage(true, "停止指定设备成功", null);
        } else {
            logger.info("停止指定设备失败");
            return new ResponseMessage(false, "指定的设备尚未被开启", null);
        }
    }

    @PostMapping("/deleteDevice")
    ResponseMessage deleteDevice(@RequestBody Device device) {
        Integer deviceId = device.getDeviceId();
        if (deviceMapper.deleteDevice(deviceId)) {
            deviceService.stopDevice(deviceId);
            logger.info("删除指定设备成功");
            return new ResponseMessage(true, "删除指定设备成功", null);
        } else {
            logger.info("删除指定设备失败");
            return new ResponseMessage(false, "删除指定设备失败", null);
        }
    }


    @GetMapping("/getDevicesByOwnerId")
    ResponseMessage getDevicesByOwnerId(Integer ownerId) {
        List<Device> deviceList = deviceMapper.getDevicesByOwnerId(ownerId);
        return ResponseMessage.success("设备列表查询成功", deviceList);
    }

    @GetMapping("/getAllDevices")
    ResponseMessage getAllDevices() {
        List<Device> deviceList = deviceMapper.getAllDevices();
        return ResponseMessage.success("设备列表查询成功", deviceList);
    }

    @PostMapping("/alterDevice")
    ResponseMessage alterDevice(@RequestBody Device device) {
        if (deviceService.alterDevice(device)) {
            logger.info("修改设备信息成功");
            return ResponseMessage.success("修改设备信息成功", device);
        } else {
            return ResponseMessage.fail("修改设备信息失败", null);
        }
    }

    @PostMapping("/test")
    ResponseMessage test(@RequestBody JSONObject jsonObject) {
        System.out.println(jsonObject);
        return ResponseMessage.success("info", jsonObject);
    }


}
